/*
 * @Author: 莫宗蓝
 * @Description: 鹰眼视图
 */
let camera = agcim.camera;
let PickerHelper = agcim.interactive.PickerHelper;
let canvas = CIM.viewer.canvas;
let width = canvas.clientWidth;
let height = canvas.clientHeight;

export default class {
  constructor(viewer) {
    this.minViewer = undefined;
    this.shape = {
      points: [],
      rect: undefined,
      entity: undefined,
    };
    this.pickerHelper = undefined;
    this.startPosition = undefined;
    this.endPosition = undefined;
    this.isStartRect = false;
    this.redRec = undefined;
    this.minMapRectangle = undefined;
    this.mainMapChangeTimer = undefined;
    this.viewer = viewer;
    this.addMinBaseLayerTimer = undefined;
    this.lastCartesian3_UL = undefined;
    this.lastCartesian3_LR = undefined;
    this.minRedMapRectangle = undefined;
  }
  /**
   * @description 用于创建鹰眼图
   * @param {*} minMap 指鹰眼图的DOM id名称
   */
  creatMap(minMap) {
    this.minViewer = new Cesium.Viewer(minMap, {
      infoBox: false,
      geocoder: false,
      fullscreenButton: false,
      homeButton: false, //是否显示Home按钮
      sceneModePicker: false, //是否显示3D/2D选择器
      navigationHelpButton: false, //是否显示右上角的帮助按钮
      navigationInstructionsInitiallyVisible: false,
      animation: false, //是否创建动画小器件，左下角仪表
      timeline: false, //是否显示时间轴
      fullscreenButtion: false, //是否显示全屏按钮
      vrButton: false,
      selectionIndicator: false, //是否显示选取指示器组件
      baseLayerPicker: false,
      sceneMode: Cesium.SceneMode.SCENE2D,
      mapMode2D: Cesium.MapMode2D.ROTATE,
      imageryProvider: new Cesium.TileMapServiceImageryProvider({
        url: Cesium.buildModuleUrl("Assets/Textures/NaturalEarthII"),
        fileExtension: 'jpg'
      })
    });
    this.minViewer._cesiumWidget._creditContainer.style.display = "none"; //隐藏版权信息
    this.minMapSetView();
    this.pickerHelper = new PickerHelper(this.minViewer);
    this.setCameraController(this.minViewer, false);
    this.minRedMapRectangle = this.getRedRectangle(this.minMapRectangle);
    this.redRec = this.minViewer.entities.add({
      rectangle: {
        coordinates: this.minRedMapRectangle,
        fill: false,
        outline: true,
        outlineColor: Cesium.Color.RED,
        outlineWidth: 10,
      },
    });
    this.setInputActionLeftDown(this.minViewer);
    this.setInputActionMouseMove(this.minViewer);
    this.setInputActionLeftUp(this.minViewer);
  }
  /**
   * @description 用于获取红色框的矩形框范围
   * @param {*} rectangle
   * @return {*}
   */
  getRedRectangle(rectangle) {
    let half_EastToWest = (rectangle.east - rectangle.west) / 2;
    let half_NorthToSouth = (rectangle.north - rectangle.south) / 2;
    let offeset = 1 / 2;
    let newRec = new Cesium.Rectangle(
      rectangle.west + offeset * half_EastToWest,
      rectangle.south + offeset * half_NorthToSouth,
      rectangle.east - offeset * half_EastToWest,
      rectangle.north - offeset * half_NorthToSouth
    );
    return newRec;
  }

  /**
   *  鹰眼图鼠标左键按下事件绘制最小矩形
   * @param {*} viewer
   */
  setInputActionLeftDown(viewer) {
    this.pickerHelper.on("LEFT_DOWN", (event) => {
      let cartesian = viewer.scene.camera.pickEllipsoid(event.position);
      if (this.shape.entity) {
        viewer.entities.remove(this.shape.entity);
        this.shape.entity = null;
      }
      if (cartesian) {
        // 绘制最小矩形
        this.startPosition = event.position;
        this.shape.points.push(
          viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian)
        );
        this.shape.rect = Cesium.Rectangle.fromCartographicArray(
          this.shape.points
        );
        this.shape.rect.east += 0.000001;
        this.shape.rect.north += 0.000001;
        this.shape.entity = viewer.entities.add({
          rectangle: {
            coordinates: this.shape.rect,
            material: Cesium.Color.YELLOW.withAlpha(0.4),
            outline: true,
            outlineWidth: 2,
            outlineColor: Cesium.Color.RED,
            height: 0,
          },
          name: "agRectangle",
        });
        this.isStartRect = true;
      }
    });
  }
  /**
   * @description 鼠标漫游事件，更新矩形
   * @param {*} viewer
   */
  setInputActionMouseMove(viewer) {
    this.pickerHelper.on("MOUSE_MOVE", (event) => {
      if (this.shape.points.length == 0 || !this.isStartRect) {
        return;
      }
      let cartesian = viewer.scene.camera.pickEllipsoid(event.endPosition);
      if (cartesian) {
        // 更新矩形坐标
        this.shape.points[1] =
          viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian);
        this.shape.rect = Cesium.Rectangle.fromCartographicArray(
          this.shape.points
        );
        if (this.shape.rect.west == this.shape.rect.east) {
          this.shape.rect.east += 0.000001;
        }
        if (this.shape.rect.south == this.shape.rect.north) {
          this.shape.rect.north += 0.000001;
        }
        this.shape.entity.rectangle.coordinates = this.shape.rect;
      }
    });
  }
  /**
   * @description 鼠标按开事件，按开时更新矩形与主图相机中心坐标
   * @param {*} viewer
   */
  setInputActionLeftUp(viewer) {
    this.pickerHelper.on("LEFT_UP", (event) => {
      this.isStartRect = false;
      this.endPosition = event.position;
      // 在鹰眼图中绘制矩形,主地图缩放到绘制矩形的范围
      if (
        Math.abs(this.startPosition.x - this.endPosition.x) > 1 ||
        Math.abs(this.startPosition.y - this.endPosition.y) > 1
      ) {
        CIM.viewer.camera.setView({
          destination: this.shape.rect,
        });
      } else {
        // 点击鹰眼图,主地图平移到点击点
        this.setView(viewer, event);
      }
      if (this.shape.entity) {
        viewer.entities.remove(this.shape.entity);
        this.shape.entity = null;
        this.shape.points = [];
      }
    });
  }
  /**
   * @description 主地图平移到点击点
   */
  setView(viewer, event) {
    //获取小图点击的中心坐标球面的，不带相机高度
    let cartesian = viewer.scene.camera.pickEllipsoid(event.position);
    let clickPosition = Cesium.Cartographic.fromCartesian(cartesian)
    clickPosition.longitude *= (180.0 / Math.PI);
    clickPosition.latitude *= (180.0 / Math.PI);
    let heading = this.viewer.camera.heading;
    let pitch = this.viewer.camera.pitch;
    let roll = this.viewer.camera.roll;
    let positionCartographicHeight = viewer.camera.positionCartographic.height; //获取Cartographic的高度
    //获取主图的相机高度
    let cameraDegrees = Cesium.Cartographic.fromCartesian(this.viewer.camera.position);
    clickPosition.height = cameraDegrees.height;
    if (this.viewer.scene.mode === 3) { //3D视图的高度直接取相机的高度
      this.viewer.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(clickPosition.longitude, clickPosition.latitude, clickPosition.height),
        orientation: {
          heading: heading,
          pitch: pitch,
          roll: roll
        }
      });
    } else if (this.viewer.scene.mode === 2) { //2D视图，取CartographicHeight
      this.viewer.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(clickPosition.longitude, clickPosition.latitude,positionCartographicHeight),
      });
    } else { //哥伦布视图，取CartographicHeight
      this.viewer.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(clickPosition.longitude, clickPosition.latitude, positionCartographicHeight),
        orientation: {
          heading: heading,
          pitch: pitch,
          roll: roll
        }
      });
    }

  }
  /**
   * @description 移除viewer的鼠标按下、移动、按开事件
   * @param {*} viewer
   */
  removeInputAction(viewer) {
    if (viewer) {
      this.pickerHelper.remove("LEFT_DOWN");
      this.pickerHelper.remove("MOUSE_MOVE");
      this.pickerHelper.remove("LEFT_UP");
      this.pickerHelper.off();
    }
  }
  /**
   * @description 监听主图变化并更新鹰眼图
   */
  mainMapExtentChange() {
    //弃用相机监听变化事件，刷新频率太慢
    if (this.minViewer) {
      this.mainMapChangeTimer = setInterval(() => {
        this.minViewer.entities.remove(this.redRec);
        this.minRedMapRectangle = this.getRedRectangle(this.minMapRectangle);
        this.redRec = this.minViewer.entities.add({
          rectangle: {
            coordinates: this.minRedMapRectangle,
            fill: false,
            outline: true,
            outlineColor: Cesium.Color.RED,
            outlineWidth: 2,
          },
        });
        this.minMapSetView();
      }, 100);
    }
  }
  /**
   * @description 设置鹰眼图视图中心
   */
  minMapSetView() {
    this.minMapRectangle = this.getMinMapRectangle(0.001);
    this.minViewer.camera.setView({
      destination: this.minMapRectangle,//Cesium.Cartographic.toCartesian(positionCartographic),
    });
  }
  /**
   *
   * @description 获得鹰眼图的屏幕范围
   * @param {*} offeset
   * @return {*}
   */
  getMinMapRectangle(offeset=0) {
    //分别获取左上、右下的笛卡尔坐标
    //小角度的平视会导致拾取出现问题
    let Cartesian3_UL = this.viewer.camera.pickEllipsoid({ x: 0, y: 0 }, this.viewer.scene.globe.ellipsoid);
    let Cartesian3_LR = this.viewer.camera.pickEllipsoid({ x: width, y: height }, this.viewer.scene.globe.ellipsoid);
    if(!Cartesian3_UL){
      Cartesian3_UL = this.lastCartesian3_UL;
    }else{
      this.lastCartesian3_UL = Cartesian3_UL;
    }
    if(!Cartesian3_LR){
      Cartesian3_LR = this.lastCartesian3_LR;
    }else{
      this.lastCartesian3_LR = Cartesian3_LR;
    }
    
    //将左上、右下的笛卡尔坐标转成Cartographic坐标
    let Cartographic_UL = Cesium.Cartographic.fromCartesian(Cartesian3_UL)
    let Cartographic_LR = Cesium.Cartographic.fromCartesian(Cartesian3_LR);

    let west = (Cartographic_UL.longitude<Cartographic_LR.longitude)?Cartographic_UL.longitude:Cartographic_LR.longitude;
    let east = (Cartographic_LR.longitude>Cartographic_UL.longitude)?Cartographic_LR.longitude:Cartographic_UL.longitude;
    let north = (Cartographic_UL.latitude>Cartographic_LR.latitude)?Cartographic_UL.latitude:Cartographic_LR.latitude;
    let south = (Cartographic_LR.latitude<Cartographic_UL.latitude)?Cartographic_LR.latitude:Cartographic_UL.latitude;

    let newRec = new Cesium.Rectangle(
      west - offeset,
      south - offeset,
      east + offeset,
      north + offeset
    );
    return newRec;
  }

  /**
   * @description 设置控制相机操作事件，
   * @param {} isEnable true 或者 false
   */
  setCameraController(viewer, isEnable) {
    camera.camera.setCameraController(viewer, {
      enableRotate: isEnable,
      enableTranslate: isEnable,
      enableZoom: isEnable,
      enableTilt: isEnable,
      enableLook: isEnable,
    });
  }
  /**
   * @description 重置数据状态
   */
  destroy() {
    if (this.redRec) {
      this.minViewer.entities.remove(this.redRec);
    }
    this.redRec = undefined;
    clearInterval(this.mainMapChangeTimer);
    this.mainMapChangeTimer = undefined;
    this.shape = {
      points: [],
      rect: undefined,
      entity: undefined,
    };
    this.lastCartesian3_UL = undefined;
    this.lastCartesian3_LR = undefined;
  }
}
